package com.wangzhen.spring.resource;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassRelativeResourceLoader;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

public class ResourceLoadDemo {

    public static void main(String[] args) throws IOException {
        // 演示1：通过ResourceLoader的默认实现DefaultResourceLoad来加载一个classpath下的路径
        DefaultResourceLoader loader = new DefaultResourceLoader();
        Resource resource = loader.getResource("classpath:META-INF/addr.properties");
        System.out.println(IOUtils.readLines(resource.getInputStream()));
        // 演示2：通过DefaultResourceLoader来加载一个指定全路径的file
        resource = loader.getResource("file:/Users/wangzhen/Downloads/codebasespring/spring-resource/src/main/resources/META-INF/addr.properties");
        System.out.println(IOUtils.readLines(resource.getInputStream()));
        // 演示3：通过DefalutResourceLoade来加载一个http资源
        resource = loader.getResource("https://read.qidian.com/chapter/O_sTbSZAqc_MQzCecGvf7A2/T6pxo8y0Aqn4p8iEw--PPw2");
        System.out.println(IOUtils.readLines(resource.getInputStream()));


        //演示4：通过FileSystemResourceLoader 来加载一个文件，但是文件的路径要以"//"开头
        FileSystemResourceLoader fileSystemResourceLoader = new FileSystemResourceLoader();
        // 这个类很怪异，或者现在没有理解，不明白在其内部实现的时候为什么要判断是"/"开头的，就把"/"给去掉
        //resource = fileSystemResourceLoader.getResource("//Users/wangzhen/Downloads/codebasespring/spring-resource/src/main/resources/META-INF/addr.properties");
        // 改进版：
        resource = fileSystemResourceLoader.getResource("file:/Users/wangzhen/Downloads/codebasespring/spring-resource/src/main/resources/META-INF/addr.properties");
        System.out.println(IOUtils.readLines(resource.getInputStream()));

        //演示5：通过通配符的方式获取【指定目录】下的通配文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new FileSystemResourceLoader());
        Resource[] resources = resolver.getResources("file:/Users/wangzhen/Downloads/codebasespring/spring-resource/src/main/resources/META-INF/*.properties");
        for (Resource res : resources) {
            System.err.println(IOUtils.readLines(res.getInputStream()));
        }

    }
}
